<template>
	<el-dialog v-model="visible" :title="isEdit ? '编辑任务' : '新增任务'" width="600px" :before-close="handleClose"
		destroy-on-close draggable top="5vh" :close-on-click-modal="false" :close-on-press-escape="false"
		class="task-edit-dialog">
		<div class="dialog-content-wrapper">
			<el-form ref="taskFormRef" :model="taskForm" :rules="formRules" label-width="100px" label-position="right"
				size="default">
				<el-row :gutter="20">
					<el-col :span="24">
						<el-form-item label="任务名称" prop="name">
							<el-input v-model="taskForm.name" placeholder="请输入任务名称（唯一标识）" :disabled="isEdit" clearable
								maxlength="100" show-word-limit />
						</el-form-item>
					</el-col>
				</el-row>

				<el-row :gutter="20">
					<el-col :span="24">
						<el-form-item label="任务描述" prop="desc">
							<el-input v-model="taskForm.desc" type="textarea" :rows="3" placeholder="请输入任务描述"
								clearable maxlength="500" show-word-limit />
						</el-form-item>
					</el-col>
				</el-row>

				<el-row :gutter="20">
					<el-col :span="12">
						<el-form-item label="调度类型" prop="type">
							<el-select v-model="taskForm.type" placeholder="请选择调度类型" style="width: 100%;"
								@change="handleTypeChange">
								<el-option label="间隔执行" value="interval" />
								<el-option label="每日执行" value="daily" />
								<el-option label="每周执行" value="weekly" />
								<el-option label="每月执行" value="monthly" />
								<el-option label="Cron表达式" value="cron" />
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="是否启用" prop="enabled">
							<el-switch v-model="taskForm.enabled" active-text="启用" inactive-text="禁用"
								:active-value="true" :inactive-value="false" />
						</el-form-item>
					</el-col>
				</el-row>

				<!-- 调度配置 -->
				<el-card shadow="never" style="margin-bottom: 20px; border: 1px dashed var(--el-border-color);">
					<template #header>
						<span style="color: var(--el-color-primary); font-weight: 500;">
							<el-icon>
								<Setting />
							</el-icon>
							调度配置
						</span>
					</template>

					<!-- 间隔执行设置 -->
					<el-form-item v-if="taskForm.type === 'interval'" label="执行间隔" prop="interval">
						<el-input-number v-model="taskForm.interval" :min="1" :max="86400" placeholder="间隔秒数"
							style="width: 100%;" controls-position="right" />
						<div class="form-help-text">单位：秒，范围：1-86400（1秒到24小时）</div>
					</el-form-item>

					<!-- 每日执行设置 -->
					<el-form-item v-if="taskForm.type === 'daily'" label="执行时间" prop="time">
						<el-time-picker v-model="taskForm.time" format="HH:mm" value-format="HH:mm"
							placeholder="选择执行时间" style="width: 100%;" />
					</el-form-item>

					<!-- 每周执行设置 -->
					<template v-if="taskForm.type === 'weekly'">
						<el-form-item label="执行星期" prop="day_of_week">
							<el-select v-model="taskForm.day_of_week" placeholder="选择星期几" style="width: 100%;">
								<el-option label="周一" :value="1" />
								<el-option label="周二" :value="2" />
								<el-option label="周三" :value="3" />
								<el-option label="周四" :value="4" />
								<el-option label="周五" :value="5" />
								<el-option label="周六" :value="6" />
								<el-option label="周日" :value="7" />
							</el-select>
						</el-form-item>
						<el-form-item label="执行时间" prop="time">
							<el-time-picker v-model="taskForm.time" format="HH:mm:ss" value-format="HH:mm:ss"
								placeholder="选择执行时间" style="width: 100%;" />
						</el-form-item>
					</template>

					<!-- 每月执行设置 -->
					<template v-if="taskForm.type === 'monthly'">
						<el-form-item label="执行日期" prop="day_of_month">
							<el-input-number v-model="taskForm.day_of_month" :min="1" :max="31" placeholder="每月几号执行"
								style="width: 100%;" controls-position="right" />
							<div class="form-help-text">范围：1-31，如果某月没有该日期则跳过</div>
						</el-form-item>
						<el-form-item label="执行时间" prop="time">
							<el-time-picker v-model="taskForm.time" format="HH:mm:ss" value-format="HH:mm:ss"
								placeholder="选择执行时间" style="width: 100%;" />
						</el-form-item>
					</template>

					<!-- Cron表达式设置 -->
					<el-form-item v-if="taskForm.type === 'cron'" label="Cron表达式" prop="cron">
						<el-input v-model="taskForm.cron" placeholder="请输入Cron表达式，如：0 0 12 * * *" clearable />
						<div class="form-help-text">
							格式：秒 分 时 日 月 周<br>
							示例：0 0 12 * * * （每天12:00执行）
						</div>
					</el-form-item>
				</el-card>

				<!-- 执行配置 -->
				<el-card shadow="never" style="margin-bottom: 20px; border: 1px dashed var(--el-border-color);">
					<template #header>
						<span style="color: var(--el-color-primary); font-weight: 500;">
							<el-icon>
								<Tools />
							</el-icon>
							执行配置
						</span>
					</template>

					<el-row :gutter="20">
						<el-col :span="24">
							<el-form-item label="执行类名" prop="class_name">
								<el-input v-model="taskForm.class_name" placeholder="请输入完整的类名，如：app\\task\\TestTask"
									clearable />
								<div class="form-help-text">
									完整的类名，包含命名空间
								</div>
							</el-form-item>
						</el-col>
					</el-row>

					<el-row :gutter="20">
						<el-col :span="24">
							<el-form-item label="执行方法" prop="method_name">
								<el-input v-model="taskForm.method_name" placeholder="方法名，默认：run" disabled />
							</el-form-item>
						</el-col>
					</el-row>

					<el-row :gutter="20">
						<el-col :span="24">
							<el-form-item label="日志记录" prop="log_level">
								<el-radio-group v-model="taskForm.log_level">
									<el-radio value="full">完整日志</el-radio>
									<el-radio value="error_only">仅错误日志</el-radio>
								</el-radio-group>
								<div class="form-help-text" style="color: #f56c6c;">
									对于执行频率非常高的任务，请不要选择完整日志，会导致日志数据量巨大。
								</div>
							</el-form-item>
						</el-col>
					</el-row>
				</el-card>
			</el-form>
		</div>

		<template #footer>
			<div class="dialog-footer">
				<el-button @click="handleClose">取消</el-button>
				<el-button type="primary" @click="handleSubmit" :loading="submitLoading">
					{{ isEdit ? '更新任务' : '创建任务' }}
				</el-button>
			</div>
		</template>
	</el-dialog>
</template>

<script>
import { ElMessage, ElMessageBox } from 'element-plus'
import { Setting, Tools } from '@element-plus/icons-vue'
import { markRaw } from 'vue'

export default {
	name: 'TaskEdit',
	components: {
		Setting: markRaw(Setting),
		Tools: markRaw(Tools),
	},
	emits: ['taskUpdated'],
	data() {
		return {
			visible: false,
			isEdit: false,
			submitLoading: false,
			taskForm: {
				id: null,
				name: '',
				desc: '',
				type: 'interval',
				enabled: true,
				class_name: '',
				method_name: 'run',
				log_level: 'full',
				// 调度配置相关
				interval: 60,
				time: '00:00:00',
				day_of_week: 1,
				day_of_month: 1,
				cron: ''
			},
			formRules: {
				name: [
					{ required: true, message: '请输入任务名称', trigger: 'blur' },
					{ min: 1, max: 100, message: '任务名称长度在 1 到 100 个字符', trigger: 'blur' },
					{ pattern: /^[a-zA-Z][a-zA-Z0-9_]*$/, message: '任务名称必须以字母开头，只能包含字母、数字和下划线', trigger: 'blur' }
				],
				desc: [
					{ max: 500, message: '描述不能超过 500 个字符', trigger: 'blur' }
				],
				type: [
					{ required: true, message: '请选择调度类型', trigger: 'change' }
				],
				class_name: [
					{ required: true, message: '请输入执行类名', trigger: 'blur' },
					{ max: 255, message: '类名不能超过 255 个字符', trigger: 'blur' }
				],
				method_name: [
					{ required: true, message: '请输入执行方法名', trigger: 'blur' },
					{ max: 100, message: '方法名不能超过 100 个字符', trigger: 'blur' }
				],
				log_level: [
					{ required: true, message: '请选择日志记录级别', trigger: 'change' }
				],
				interval: [
					{ required: true, message: '请设置执行间隔', trigger: 'blur' },
					{ type: 'number', min: 1, max: 86400, message: '间隔时间必须在 1-86400 秒之间', trigger: 'change' }
				],
				time: [
					{ required: true, message: '请选择执行时间', trigger: 'change' }
				],
				day_of_week: [
					{ required: true, message: '请选择执行星期', trigger: 'change' }
				],
				day_of_month: [
					{ required: true, message: '请设置执行日期', trigger: 'blur' },
					{ type: 'number', min: 1, max: 31, message: '日期必须在 1-31 之间', trigger: 'change' }
				],
				cron: [
					{ required: true, message: '请输入 Cron 表达式', trigger: 'blur' },
					{ pattern: /^(\S+\s+){5}\S+$/, message: '请输入正确的 Cron 表达式格式', trigger: 'blur' }
				]
			}
		}
	},
	created() {
		
	},
	methods: {
		// 打开对话框
		open(task = null) {
			this.isEdit = !!task
			if (task) {
				this.fillFormWithTask(task)
			} else {
				this.resetForm()
			}
			this.visible = true
		},
		
		// 填充表单数据（编辑模式）
		fillFormWithTask(task) {
			this.taskForm = {
				id: task.id,
				name: task.name || '',
				desc: task.desc || '',
				type: task.type || 'interval',
				enabled: Boolean(task.enabled),
				class_name: task.class_name || '',
				method_name: task.method_name || 'run',
				log_level: task.log_level,
				// 调度配置相关
				interval: 60,
				time: '00:00:00',
				day_of_week: 1,
				day_of_month: 1,
				cron: ''
			}
			
			// 解析调度配置
			if (task.schedule_config) {
				try {
					const config = typeof task.schedule_config === 'string' 
						? JSON.parse(task.schedule_config) 
						: task.schedule_config
					
					if (task.type === 'interval') {
						this.taskForm.interval = config.interval || 60
					} else if (task.type === 'daily') {
						this.taskForm.time = config.time || '00:00:00'
					} else if (task.type === 'weekly') {
						this.taskForm.day_of_week = config.day_of_week || 1
						this.taskForm.time = config.time || '00:00:00'
					} else if (task.type === 'monthly') {
						this.taskForm.day_of_month = config.day_of_month || 1
						this.taskForm.time = config.time || '00:00:00'
					} else if (task.type === 'cron') {
						this.taskForm.cron = config.cron || ''
					}
				} catch (e) {
					console.warn('解析调度配置失败:', e)
				}
			}
		},
		
		// 重置表单
		resetForm() {
			this.taskForm = {
				id: null,
				name: '',
				desc: '',
				type: 'interval',
				enabled: true,
				class_name: '',
				method_name: 'run',
				log_level: 'full',
				interval: 60,
				time: '00:00:00',
				day_of_week: 1,
				day_of_month: 1,
				cron: ''
			}
			
			if (this.$refs.taskFormRef) {
				this.$refs.taskFormRef.clearValidate()
			}
		},
		
		// 处理调度类型变更
		handleTypeChange() {
			if (this.$refs.taskFormRef) {
				// 清除之前的验证错误
				this.$refs.taskFormRef.clearValidate()
			}
		},
		
		// 检查高频任务的日志配置
		async checkHighFrequencyTaskLog() {
			// 只有间隔执行且间隔小于10分钟(600秒)且选择了完整日志才需要警告
			if (this.taskForm.type === 'interval' && 
				this.taskForm.interval < 600 && 
				this.taskForm.log_level === 'full') {
				
				try {
					await ElMessageBox.confirm(
						`检测到您配置的任务执行间隔为 ${this.taskForm.interval} 秒（小于10分钟），但选择了完整日志记录。这可能会产生大量日志数据，建议选择"仅错误日志"。\n\n是否继续保存当前配置？`,
						'高频任务日志警告',
						{
							confirmButtonText: '继续保存',
							cancelButtonText: '重新配置',
							type: 'warning',
							dangerouslyUseHTMLString: false
						}
					)
					return true
				} catch {
					// 用户选择取消，返回false
					return false
				}
			}
			return true
		},
		
		// 提交表单
		async handleSubmit() {
			try {
				// 验证表单
				await this.$refs.taskFormRef.validate()
				
				// 检查高频任务的日志配置
				const shouldContinue = await this.checkHighFrequencyTaskLog()
				if (!shouldContinue) {
					return
				}
				
				this.submitLoading = true
				
				// 构建提交数据
				const submitData = this.buildSubmitData()
				
				// 调用保存API
				const { save } = await import('../api')
				const response = await save(submitData)
				
				if (response.code === 200) {
					ElMessage.success(this.isEdit ? '任务更新成功' : '任务创建成功')
					this.handleClose()
					this.$emit('taskUpdated')
				} else {
					throw new Error(response.message || '保存失败')
				}
			} catch (error) {
				if (error.name !== 'ElementPlusError') {
					ElMessage.error('保存失败: ' + error.message)
				}
			} finally {
				this.submitLoading = false
			}
		},
		
		// 构建提交数据
		buildSubmitData() {
			const data = {
				name: this.taskForm.name,
				desc: this.taskForm.desc,
				type: this.taskForm.type,
				enabled: this.taskForm.enabled ? 1 : 0,
				class_name: this.taskForm.class_name,
				method_name: this.taskForm.method_name,
				log_level: this.taskForm.log_level,
				schedule_config: this.buildScheduleConfig()
			}
			
			if (this.isEdit && this.taskForm.id) {
				data.id = this.taskForm.id
			}
			
			return data
		},
		
		// 构建调度配置
		buildScheduleConfig() {
			const config = {}
			
			switch (this.taskForm.type) {
				case 'interval':
					config.interval = this.taskForm.interval
					break
				case 'daily':
					config.time = this.taskForm.time
					break
				case 'weekly':
					config.day_of_week = this.taskForm.day_of_week
					config.time = this.taskForm.time
					break
				case 'monthly':
					config.day_of_month = this.taskForm.day_of_month
					config.time = this.taskForm.time
					break
				case 'cron':
					config.cron = this.taskForm.cron
					break
			}
			
			return config
		},
		
		// 关闭对话框
		handleClose() {
			this.visible = false
			this.$nextTick(() => {
				this.resetForm()
			})
		}
	}
}
</script>

<style lang="less" scoped>
.dialog-footer {
	text-align: right;
}

.form-help-text {
	font-size: 12px;
	color: var(--el-text-color-secondary);
	line-height: 1.4;
	margin-top: 4px;
}

.dialog-content-wrapper {
	
	padding-right: 10px;
}

:deep(.el-dialog) {
	margin-top: 5vh !important;
	margin-bottom: 5vh !important;
	height: 85vh;
	max-height: 85vh;
	display: flex;
	flex-direction: column;
}

:deep(.el-dialog__header) {
	flex-shrink: 0;
	padding: 20px 20px 10px 20px;
	margin: 0;
	border-bottom: 1px solid var(--el-border-color-lighter);
}

:deep(.el-dialog__body) {
	flex: 1;
	padding: 20px;
	overflow: hidden;
	display: flex;
	flex-direction: column;
}

:deep(.el-dialog__footer) {
	flex-shrink: 0;
	padding: 10px 20px 20px 20px;
	margin: 0;
	border-top: 1px solid var(--el-border-color-lighter);
}

:deep(.el-form-item) {
	margin-bottom: 18px;
}

:deep(.el-form-item__label) {
	font-weight: 500;
	color: var(--el-text-color-primary);
}

:deep(.el-card__header) {
	padding: 12px 16px;
	background-color: var(--el-bg-color-page);
}

:deep(.el-card__body) {
	padding: 16px;
}

:deep(.el-input-number) {
	width: 100%;
}

:deep(.el-textarea) {
	.el-textarea__inner {
		font-family: 'Consolas', 'Monaco', monospace;
	}
}

</style>